package com.ljw.test.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.Scroller;
import android.widget.TextView;

import com.ljw.test.R;

public class WordWrapView extends ViewGroup {
    private CheckBox expandButton;
    private int keyBoardHeight;
    private int displayHeight;

    public void setKeyBoardHeight(int keyBoardHeight) {
        this.keyBoardHeight = keyBoardHeight;
    }

    public void setExpandButton(CheckBox expandButton) {
        this.expandButton = expandButton;
    }

    private boolean state;
    private int padding_hor = 0;//子view水平方向padding
    private int padding_vertical = 0;//子view垂直方向padding
    private int margin_hor = 0;//子view之间的水平间距
    private int margin_vertical = 0;//行间距
    private Scroller scroller = new Scroller(getContext());
    private int num = 0;//最多字个数

    private int screenHeight;
    private int widthSpecSize;
    private int acturalWith;
    private int layoutHeight;

    private int rowHeight = 130;

    public int getRowHeight() {
        return rowHeight;
    }

    /**
     * @param context
     */
    public WordWrapView(Context context) {
        super(context);
    }

    /**
     * @param context
     * @param attrs
     */
    public WordWrapView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initAttrs(context, attrs);
    }

    /**
     * @param context
     * @param attrs
     * @param defStyle
     */
    public WordWrapView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initAttrs(context, attrs);
    }

    //获取属性值
    private void initAttrs(Context context, AttributeSet attrs) {
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.WordWrapView);
        padding_hor = (int) ta.getDimension(R.styleable.WordWrapView_padding_hor, 30);
        padding_vertical = (int) ta.getDimension(R.styleable.WordWrapView_padding_vertical, 25);
        margin_hor = (int) ta.getDimension(R.styleable.WordWrapView_margin_hor, 0);
        margin_vertical = (int) ta.getDimension(R.styleable.WordWrapView_margin_vertial, 0);
        ta.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        measureChildren(widthMeasureSpec, heightMeasureSpec);

        widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);

        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            child.setPadding(padding_hor, padding_vertical, padding_hor, padding_vertical);
            child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
        }

        if (!state) {
            displayHeight = rowHeight;
        } else {
//            screenHeight = 604 + 100;
            displayHeight = keyBoardHeight + rowHeight;
//            System.out.println(keyBoardHeight + ":height");
        }

        setMeasuredDimension(widthSpecSize, displayHeight);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int childCount = getChildCount();
        //实际宽度
        acturalWith = r - l;
        int x = 0;
        int y = 0;
        int rows = 1;

        for (int i = 0; i < childCount; i++) {//判断累积高度
            View view = getChildAt(i);
            int width = view.getMeasuredWidth();
            int height = view.getMeasuredHeight();
            x += width + margin_hor;
            if (x > acturalWith - margin_hor) {
                if (i != 0) {
                    x = width + margin_hor;
                    rows++;
                }
            }

            //当一个子view长度超出父view长度时
            if (x > acturalWith - margin_hor) {
                if (view instanceof TextView) {//判断单个高度
                    TextView tv = (TextView) view;
                    if (num == 0) {
                        int wordNum = tv.getText().toString().length();
                        num = wordNum * (acturalWith - 2 * margin_hor - 2 * padding_hor) / (width - 2 * padding_hor) - 1;
                    }
                    String text = tv.getText().toString();
                    text = text.substring(0, num) + "...";
                    tv.setText(text);
                }
                x = acturalWith - margin_hor;
                width = acturalWith - 2 * margin_hor;
            }
            y = rows * (height + margin_vertical);
            layoutHeight = y;
            view.layout(x - width, y - height, x, y);
        }
        if (rows > 1) {
            expandButton.setVisibility(VISIBLE);
        } else {
            expandButton.setChecked(false);
            expandButton.setVisibility(INVISIBLE);
        }

        if (state) screenHeight = y - keyBoardHeight - rowHeight;
        else screenHeight = layoutHeight - rowHeight;
    }

    private float lastDownY;
    private float mScrollStart;
    private float mScrollEnd;

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastDownY = ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                float currY = ev.getY();
                if (Math.abs(currY - lastDownY) > 20) {
                    return true;
                }
                break;
        }
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastDownY = event.getY();
                mScrollStart = getScrollX();
                break;
            case MotionEvent.ACTION_MOVE:
                float dy;
                float currentY = event.getY();

                dy = lastDownY - currentY;
                scrollBy(0, (int) dy);
                lastDownY = event.getY();
                break;
            case MotionEvent.ACTION_UP:
                mScrollEnd = getScrollY();

                if (mScrollEnd < 0) {// 最顶端：手指向下滑动，回到初始位置
                    System.out.println("1");
                    scroller.startScroll(0, getScrollY(), 0, -getScrollY());
                } else if (layoutHeight < keyBoardHeight + rowHeight && state) {
                    System.out.println("2");
                    scroller.startScroll(0, getScrollY(), 0, -getScrollY());
                } else if (mScrollEnd > screenHeight) {//已经到最底端，手指向上滑动回到底部位置
                    System.out.println("3");
                    scroller.startScroll(0, getScrollY(), 0, screenHeight - getScrollY());
                }
                postInvalidate();// 重绘执行computeScroll()
                break;
        }
        return true;//需要返回true否则down后无法执行move和up操作
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        if (scroller.computeScrollOffset()) {//是否已经滚动完成
            scrollTo(0, scroller.getCurrY());//获取当前值，startScroll（）初始化后，调用就能获取区间值
            postInvalidate();
        }
    }

    public void setState(boolean state) {
        this.state = state;
    }


    public int getPadding_hor() {
        return padding_hor;
    }

    public void setPadding_hor(int padding_hor) {
        this.padding_hor = padding_hor;
    }

    public int getPadding_vertical() {
        return padding_vertical;
    }

    public void setPadding_vertical(int padding_vertical) { this.padding_vertical = padding_vertical; }

    public int getMargin_hor() {
        return margin_hor;
    }

    public void setMargin_hor(int margin_hor) {
        this.margin_hor = margin_hor;
    }

    public int getMargin_vertical() {
        return margin_vertical;
    }

    public void setMargin_vertical(int margin_vertical) {
        this.margin_vertical = margin_vertical;
    }
}
